import React, { Component } from 'react';
import './index.scss'

class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
      pictures: [...this.props.value],
      SelectedList: [] // 被选择的图片
    }
  }
  render () {
    return (
      <div className="box">
        <header>
          <label>
            {/* <input type="checkbox"/> */}
            已选择{this.state.SelectedList.length}张
          </label>
        </header>
        <section>
          {this.state.pictures.map((item) => {
            return (
              <label key={item.id}>
                <input type="checkbox" onClick={() => {
                  this.props.onChange(item.id)
                  // 当前图片被点击,判断数组中是否存在数据,若不存在,则直接将当前图片数据添加进被点击数组中
                  if (this.state.SelectedList.length === 0) {
                    this.setState({
                      SelectedList: [...this.state.SelectedList, item]
                    })
                  } else {
                    // 若存在数据了,则判断数组中是否存在当前数据,若不存在则添加,若存在则删除
                    for (let i = 0; i < this.state.SelectedList.length; i ++) {
                      let idx = i
                      let itm = this.state.SelectedList[i]
                      if (itm.id * 1 === item.id * 1) {
                        // 数组中存在当前被点击数据,删除
                        let arr = [...this.state.SelectedList]
                        arr.splice(idx, 1)
                        this.setState({
                          SelectedList: arr
                        })
                        break // 一定要注意在删除之后跳出循环,否则他会在删除之后继续循环就会被检测出来不存在由重新添加进去了
                      } else {
                        // 数组中不存当前被点击数据,添加
                        this.setState({
                          SelectedList: [...this.state.SelectedList, item]
                        })
                      }
                    }
                  }
                }}/>
                <img src={item.url} alt=""/>
                <span>{ item.name }</span>
              </label>
            )
          })}
        </section>
      </div>
    )
  }
}

export default Index